<template>
  <el-form
    ref="formRef"
    :model="form"
    label-width="100px"
  >
    <!-- 动态表单字段 -->
    <el-form-item
      v-for="field in fields"
      :key="field.id"
      :label="field.name"
      :prop="'content.' + field.field_name"
      :rules="field.required ? [{ required: true, message: `请输入${field.name}`, trigger: 'blur' }] : []"
    >
      <el-input
        v-model="form.content[field.field_name]"
        :placeholder="`请输入${field.name}`"
      />
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { fieldApi } from '@/api/fieldApi'

const props = defineProps({
  initialData: {
    type: Object,
    default: () => ({
      id: null,
      content: {}
    })
  }
})

const emit = defineEmits(['submit'])

// 表单引用
const formRef = ref(null)

// 字段列表
const fields = ref([])
const loading = ref(false)

// 表单数据
const form = reactive({
  content: {}
})

// 监听传入数据变化，并更新表单
watch(() => props.initialData, (newData) => {
  form.content = { ...(newData?.content || {}) }
}, { deep: true, immediate: true })


// 获取字段列表
const fetchFields = async () => {
  try {
    loading.value = true
    const res = await fieldApi.getFields()
    if (res.code === 200 && Array.isArray(res.data.items)) {
      fields.value = res.data.items
    } else {
      fields.value = []
      ElMessage.error('获取字段列表失败：数据格式错误')
    }
  } catch (error) {
    console.error('Fetch fields error:', error)
    fields.value = []
    ElMessage.error('获取字段列表失败')
  } finally {
    loading.value = false
  }
}

// 表单验证
const validate = async () => {
  if (!formRef.value) return false
  try {
    await formRef.value.validate()
    return true
  } catch (error) {
    return false
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.content = {}
}

const getTransformedData = () => {
  const orderedDataFields = fields.value
    .filter(field => Object.prototype.hasOwnProperty.call(form.content, field.field_name))
    .map(field => ({
      field_name: field.field_name,
      description: form.content[field.field_name]
    }));
  
  return { fields: orderedDataFields };
};

// 暴露方法给父组件
defineExpose({
  validate,
  resetForm,
  getTransformedData
})

// 初始化
onMounted(() => {
  fetchFields()
})
</script>

<style lang="scss" scoped>
.el-form {
  max-width: 600px;
}
</style> 